package com.example.quiz.service.impl;

import com.example.quiz.dao.QuizRepository;
import com.example.quiz.entity.Question;
import com.example.quiz.entity.QuestionWrapper;
import com.example.quiz.entity.Quiz;
import com.example.quiz.entity.Response;
import com.example.quiz.feign.QuizInterface;
import com.example.quiz.service.QuizService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class QuizServiceImpl implements QuizService {
    @Autowired
    QuizRepository quizRepository;

    @Autowired
    QuizInterface quizInterface;

//    @Autowired
//    QuestionRepository questionRepository;

    @Override
    public ResponseEntity<Integer> createQuiz(String category, int numQuestions, String title) {
        List<Integer> questionIds = quizInterface.generateQuestionsforQuiz(category, numQuestions).getBody();
        Quiz quiz = new Quiz();
        quiz.setTitle(title);
        quiz.setQuestionsid(questionIds);
        Quiz generatedQuiz = quizRepository.saveAndFlush(quiz);

//        return ResponseEntity.ok("Quiz created successfully");
        return ResponseEntity.ok(generatedQuiz.getId());

    }

    @Override
    public ResponseEntity<List<QuestionWrapper>> getQuizQuestions(Integer id) {
        Quiz quiz = quizRepository.findById(id).get();
        List<Integer> questionIds = quiz.getQuestionsid();
        ResponseEntity<List<QuestionWrapper>> questionWrappers = quizInterface.getQuestionsfromIds(questionIds);



//        List<Question> questions = quiz.get().getQuestionsid();
//        List<QuestionWrapper> questionWrappers = new ArrayList<>();

        return questionWrappers;
    }

    @Override
    public Integer calculateScore(Integer id, List<Response> responses) {
        Quiz quiz = quizRepository.findById(id).get();
        List<Integer> questionsid = quiz.getQuestionsid();
        List<QuestionWrapper> questionsfromIds = quizInterface.getQuestionsfromIds(questionsid).getBody();
        Integer score = quizInterface.getScore(responses).getBody();

//        List<Question> questions = quiz.get().getQuestionsid();
//        System.out.println(questions);
//        int score = 0;
//        for (int i = 0; i < questions.size(); i++) {
//            String response = responses.get(i).getResponse();
//            String rightAnswer = questions.get(i).getRightAnswer();
//            if (rightAnswer.equals(response)) {
//                score++;
//            }
//        }
        return score;
    }
}
